//
//  HBWithdrawalsRecordCtrl.m
//  HuoBao
//
//  Created by 于会海 on 15/12/3.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBWithdrawalsRecordCtrl.h"
#import "MJRefresh.h"
#import "HBLoginManager.h"
#import "HBBuyrecordCell.h"
#import "HBGetDistillRecordInfo.h"
#import "HBGetDistillRecordItemInfo.h"
#import "HBGetDistillRecordMonthInfo.h"
#import "HBGetDistillRecordParam.h"
#import "HBGetDistillRecordParser.h"

@interface HBWithdrawalsRecordCtrl ()<UITableViewDataSource,UITableViewDelegate>
{
    BOOL            isFirstLogView;
    NSMutableArray* dataSource;
    HBGetDistillRecordInfo* distillInfo;
}
@property (nonatomic, strong) UITableView* myTableView;
@property (nonatomic) NSInteger pageNum;
//下拉的时候才会检测
@property (nonatomic) BOOL isRequestFinish;



@end

@implementation HBWithdrawalsRecordCtrl
#define Notify_distillRecordEndRefresh     @"Notify_distillRecordEndRefresh"
#define GetFinalresult(a,b) (isIphone4or5?a:b)
#define GetFinalResult(x,y,z,r) (IsIphone4?x:(IsIphone6P?r:(IsIphone5?y:z)))

- (void)viewWillAppear:(BOOL)animated{
    isFirstLogView = YES;
    [super viewWillAppear:YES];
    _isRequestFinish = NO;
    self.pageNum = 1;
}

- (void)makeBackViewNormal{
    UIView* back = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [back setBackgroundColor:[LCCommon getColor:@"e1e1e1"]];
    [self.view addSubview:back];
    
    UIImage* image = [UIImage imageNamed:@"distill_record"];
    UIImageView* normalBack = [[UIImageView alloc] initWithFrame:CGRectMake(0,GetFinalResult(SCREEN_HEIGHT* 45/(667-64-60), SCREEN_HEIGHT* 90/(667-64-60), SCREEN_HEIGHT* 90/(667-64-60), SCREEN_HEIGHT* 90/(667-64-60)), image.size.width, image.size.height)];
    normalBack.image = image;
    normalBack.centerX = self.view.centerX;
    [self.view addSubview:normalBack];

}

- (void)startMJRefresh{
    __weak UITableView *tableView = self.myTableView;
    __weak typeof(self) weakSelf = self;
    
    [[NSNotificationCenter defaultCenter]addObserverForName:Notify_distillRecordEndRefresh object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        if (weakSelf.isRequestFinish)
        {
            [tableView.mj_header endRefreshing];
            [tableView reloadData];
        }
    }];
    
    // 下拉刷新
    tableView.mj_header = [HBOrangeHeader headerWithRefreshingBlock:^{
        weakSelf.pageNum = 1;
        
        [weakSelf requestToGetDistillRecord];
        
        if (tableView.mj_footer)
        {
            [tableView.mj_footer resetNoMoreData];
        }
        
    }];
    //    tableView.mj_header.backgroundColor = [LCCommon getColor:Main_BackGround_Color];
    tableView.mj_header.automaticallyChangeAlpha = YES;
    
    //    tableView.mj_header.backgroundColor = [LCCommon getColor:Main_BackGround_Color];
    
    // 上拉加载
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        if (distillInfo.dataAry.count>0)
        {
            weakSelf.pageNum++;
            [weakSelf requestToGetDistillRecord];
        }
        else
        {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 结束刷新
                [tableView.mj_footer endRefreshing];
            });
        }
        
    }];
    
//    [self.myTableView.mj_header beginRefreshing];
    
    self.pageNum = 1;
    
    [self requestToGetDistillRecord];
    
}

- (void)requestToGetDistillRecord{
     [CustomLoadingView showHudToView:self.view];
    HBGetDistillRecordParam* param = [[HBGetDistillRecordParam alloc] init];
    HBGetDistillRecordParser* parser = [[HBGetDistillRecordParser alloc] init];
    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    param.pageNum = [NSString stringWithFormat:@"%ld",  (long)self.pageNum];
    
    [NetCenter getDataFromURL:Method_getDistillRecord params:param parser:parser result:^(ParserResult *myResult) {
        [CustomLoadingView hideHudForView:self.view];
        if (myResult.code==0)
        {
            HBGetDistillRecordInfo *info = (HBGetDistillRecordInfo *)myResult.result;

            if (self.pageNum==1)
            {
                distillInfo = info;
                if (distillInfo.dataAry.count==0)
                {
                    [self makeBackViewNormal];
                    
                }
                
            }
            else
            {
                [self.myTableView.mj_footer endRefreshing];
                if (info.dataAry.count>0)
                {
                    NSMutableArray *dataAry = [NSMutableArray arrayWithArray:distillInfo.dataAry];
                    HBGetDistillRecordMonthInfo *monthInfoOld = [distillInfo.dataAry lastObject];
                    HBGetDistillRecordMonthInfo *monthInfoNew = [info.dataAry firstObject];
                    if ([monthInfoOld.distillMonth isEqualToString:monthInfoNew.distillMonth])
                    {
                        NSMutableArray *arrayA = [NSMutableArray arrayWithArray:monthInfoOld.distillList];
                        [arrayA addObjectsFromArray:monthInfoNew.distillList];
                        monthInfoOld.distillList = arrayA;
                        [dataAry removeLastObject];
                        [dataAry addObject:monthInfoOld];
                        if (info.dataAry.count>1)
                        {
                            NSMutableArray *arrayB = [NSMutableArray arrayWithArray:info.dataAry];
                            [arrayB removeObjectAtIndex:0];
                            [dataAry addObjectsFromArray:arrayB];
                        }
                        
                    }
                    else
                    {
                        [dataAry addObjectsFromArray:info.dataAry];
                    }
                    distillInfo.dataAry = dataAry;
                    [self.myTableView reloadData];
                }
                else
                {
                    self.pageNum--;
                    [self.myTableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            
        }
        else
        {
            DISSMISS_ERR(myResult.message);
            if (self.pageNum>1)
            {
                self.pageNum--;
                [self.myTableView.mj_footer endRefreshing];
            }
        }
        
        if (self.pageNum==1)
        {
            self.isRequestFinish = YES;
            [[NSNotificationCenter defaultCenter] postNotificationName:Notify_distillRecordEndRefresh object:nil];
        }
        
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        DISSMISS_ERR([error description]);
        if (self.pageNum==1)
        {
            self.isRequestFinish = YES;
            [[NSNotificationCenter defaultCenter] postNotificationName:Notify_distillRecordEndRefresh object:nil];
        }
        else
        {
            self.pageNum--;
            [self.myTableView.mj_footer endRefreshing];
        }
    }];
}

- (void)buildLayout{
    [super viewWillAppear:YES];
    [self.view setBackgroundColor:[LCCommon getColor:@"e1e1e1"]];
    [self creatUI];
    [self startMJRefresh];
}

- (void)creatUI{
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-49-84-64-16) style:UITableViewStyleGrouped];
    [self.myTableView setBackgroundColor:[LCCommon getColor:@"E1E1E1"]];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.showsVerticalScrollIndicator = NO;
    self.myTableView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.myTableView];
    [self.myTableView registerNib:[UINib nibWithNibName:@"HBBuyrecordCell" bundle:nil] forCellReuseIdentifier:@"recordCell"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    

    HBGetDistillRecordMonthInfo* monthInfo = (HBGetDistillRecordMonthInfo*)distillInfo.dataAry[section];
    LLog(@"%lu",monthInfo.distillList.count);
    if (monthInfo.distillList > 0) {
        return monthInfo.distillList.count;
    }else{
        return 0;
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (distillInfo.dataAry.count>0) {
        return distillInfo.dataAry.count;
    }
    return 0;
}

- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString* identifier = @"recordCell";
    LLog(@"%lu",indexPath.section);
    HBGetDistillRecordMonthInfo *monthInfo = distillInfo.dataAry[[indexPath section]];
    HBGetDistillRecordItemInfo *itemInfo = monthInfo.distillList[indexPath.row];
    HBBuyrecordCell*    cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    LLog(@"%lu",self.pageNum);
    
    if (monthInfo.distillList.count>0) {
        itemInfo = (HBGetDistillRecordItemInfo*)monthInfo.distillList[indexPath.row];
        cell.tradBank.text = itemInfo.bankName;
        cell.tradDate.text = [LCCommon getMessageTimeStrWithTime:itemInfo.distillTime];
        cell.tradMoney.text = [NSString stringWithFormat:@"%.2f",[itemInfo.distillMoney doubleValue]];;
        cell.tradBankCardNumber.text = itemInfo.bankCardno;
        
        NSString* statusString;
        int  status = [itemInfo.distillStatus intValue];
        switch (status) {
            case 0:
                statusString = @"处理中";
                break;
            case 1:
                statusString = @"提现成功";
                cell.tradStatus.textColor = [LCCommon getColor:@"51b724"];
                break;
            case 2:
                statusString = @"提现失败";
                cell.tradMoney.textColor = [LCCommon getColor:@"f24545"];
                cell.tradStatus.textColor = [LCCommon getColor:@"f24545"];
                
                break;
                
            default:
                break;
        }
        cell.tradStatus.text = statusString;
        
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 16;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    HBGetDistillRecordMonthInfo* monthInfo;
    if (distillInfo.dataAry) {
        monthInfo = (HBGetDistillRecordMonthInfo*)distillInfo.dataAry[section];
        return monthInfo.distillMonth;
    }else{
        return @"";
    }
}

- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView* footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
    [footView setBackgroundColor:[UIColor clearColor]];
    return footView;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView* headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 16)];
    [headerView setBackgroundColor:[LCCommon getColor:@"cfcfcf"]];
    UILabel* headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH/2, 16)];
    
    HBGetDistillRecordMonthInfo* monthInfo;
    if (distillInfo.dataAry.count>0) {
        monthInfo = (HBGetDistillRecordMonthInfo*)distillInfo.dataAry[section];
        headerLabel.text = monthInfo.distillMonth;
    }
    headerLabel.font = [UIFont systemFontOfSize:11];
    headerLabel.textColor = [LCCommon getColor:@"666666"];
    [headerView addSubview:headerLabel];
    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
